package edu.lagou.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.*;

@Slf4j
@Component
public class BlackListFilter implements GlobalFilter, Ordered {

    // 模拟访问记录（实际可以去数据库或者redis中查询）
    private static Map<String, Long> visitMap = new HashMap<String, Long>();
    private static Map<String, Integer> visitCount = new HashMap<String, Integer>();
    private static int countThreshold = 4;
    private static int minuteThreshold = 5;

//    static {
//        visitMap.add("0:0:0:0:0:0:0:1"); // 模拟本机地址
//    }


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();


        URI reqUri = request.getURI();
        System.out.println(">>>>> reqUri: " + reqUri.getPath());

        if (reqUri.getPath().indexOf("/api/user/info") > -1) {
            // 检查是否有cookie
            List cookies = request.getCookies().get("token");
            if (cookies == null) {
                // 跳转到登录页面
                response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
                log.debug("=====>没有cookie: 将被拒绝访问！");
                String data = "Redirect to login page!";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }

        // 从request对象中获取客户端ip
        String clientIp = request.getRemoteAddress().getHostString();
        Long lastVisit = visitMap.get(clientIp);
        Calendar tCal = Calendar.getInstance();

        Long now = tCal.getTimeInMillis();
        int vCount = 0;
        if (lastVisit != null && (now - lastVisit) / (1000 * 60)  < minuteThreshold ) {
            vCount = visitCount.get(clientIp);
            if (vCount > countThreshold) {
                // 决绝访问，返回
                response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
                log.debug("=====>IP:" + clientIp + " 在频繁访问黑名单中，将被拒绝访问！");
                String data = "Request be denied!";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }
        visitMap.put(clientIp, tCal.getTimeInMillis());
        visitCount.put(clientIp, ++vCount);

        // 合法请求
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
